from fastapi import HTTPException, WebSocket, WebSocketDisconnect, APIRouter
from thirdpart.xf_iat.iflytek_ws_client import IflytekClient
from thirdpart.xf_iat.xfyun_service_translter import translate
import asyncio
from settings import settings
from pydantic import BaseModel


from typing import List, Dict






iflytek_translter_router = APIRouter()


class TranslateRequest(BaseModel):
    text: str
    from_lang: str
    to_lang: str

@iflytek_translter_router.post("/translate",summary= "输入要翻译语言")
async def translate_text(req: TranslateRequest):
    # 校验语言是否合法
    if req.from_lang not in settings.LANG_NAME_MAP:
        raise HTTPException(status_code=400, detail=f"无效源语言代码: {req.from_lang}")
    if req.to_lang not in settings.LANG_NAME_MAP:
        raise HTTPException(status_code=400, detail=f"无效目标语言代码: {req.to_lang}")

    from_name = settings.LANG_NAME_MAP.get(req.from_lang, "未知")
    to_name = settings.LANG_NAME_MAP.get(req.to_lang, "未知")
    print(f"翻译请求: {from_name}（{req.from_lang}） -> {to_name}（{req.to_lang}）")

    try:
        result = translate(req.text, req.from_lang, req.to_lang)
        return {"result": result}
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))
    # try:
    #     result = translate(req.text, req.from_lang, req.to_lang)
    #     return {"result": result}
    # except Exception as e:
    #     raise HTTPException(status_code=400, detail=str(e))


@iflytek_translter_router.get("/languages", response_model=List[Dict[str, str]],summary= "当前支持的翻译语言")
async def get_languages():
    return [{"code": k, "name": v} for k, v in settings.LANG_NAME_MAP.items()]
